package cn.movie.dao;

import cn.movie.util.ConfigManager;

import java.io.IOException;
import java.sql.*;
import java.util.List;

/**
 * @author yellow
 * 这是一个基本dao类
 * 方法有创建连接 释放资源 查询 修改
 */
public class BaseDao {
    Connection connection = null;
    PreparedStatement pstr = null;
    ResultSet rs = null;
    int count = 0;
    /**创建连接方法*/
    public boolean getConnect(){
        String driver = ConfigManager.getConfig().getVal("driver");
        String user = ConfigManager.getConfig().getVal("user");
        String password = ConfigManager.getConfig().getVal("password");
        String url = ConfigManager.getConfig().getVal("url");
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url,user,password);
        }catch(ClassNotFoundException e){
            e.printStackTrace();
            return  false;
        }catch(SQLException e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**释放资源*/
    public void close(){
        if(rs != null){
            try{
                rs.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        if(pstr!=null){
            try {
                pstr.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /**创建查询方法*/
    public ResultSet query(String sql,Object[] objects){
        if(getConnect()){
            try{
                pstr = connection.prepareStatement(sql);
                if(pstr!=null){
                    for(int i =0;i < objects.length;i++){
                        pstr.setObject(i+1,objects[i]);
                    }
                }
                rs = pstr.executeQuery();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        return rs;
    }
    /**创建修改方法*/
    public int update(String sql,Object[] objects){
        if(getConnect()){
            try {
                pstr = connection.prepareStatement(sql);
                if(pstr!=null){
                    for(int i = 0;i < objects.length;i++){
                        pstr.setObject(i+1, objects[i]);
                    }
                }
                count = pstr.executeUpdate();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        return count;
    }
}
